package lk.icta.core.dao.impl;

import lk.icta.common.dao.impl.BaseDAO;
import lk.icta.common.web.action.BaseAction;
import lk.icta.core.dao.AppointmentScheduleDAO;
import lk.icta.core.entity.AppointmentSchedule;
import lk.icta.user.entity.User;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.Query;
import java.util.Date;
import java.util.List;

/**
 * @author Kusal Samarakoon
 */
public class AppointmentScheduleDAOImpl extends BaseDAO implements AppointmentScheduleDAO {

    @Transactional(propagation = Propagation.MANDATORY)
    public void addAppointmentSchedule(AppointmentSchedule schedule, User user) {
        logger.debug("Adding a AppointmentSchedule {}", schedule.getId());
        schedule.getLifeCycleInfo().setCreatedTimeStamp(new Date());
        schedule.getLifeCycleInfo().setCreatedUser(user);
        schedule.getLifeCycleInfo().setLastUpdatedTimeStamp(new Date());
        schedule.getLifeCycleInfo().setLastUpdatedUser(user);
        em.persist(schedule);
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    public List<AppointmentSchedule> getAllAppointmentScheduleByDSDivision(User user) {
        Query q = em.createNamedQuery("getAllAppointmentScheduleByDSDivision");
        int dsDivisionId = user.getDsDivisions().iterator().next().getId();
        q.setParameter("dsDivisionId", dsDivisionId);
        return q.getResultList();
    }

    @Transactional(propagation = Propagation.NEVER)
    public List<AppointmentSchedule> findScheduleByApplicationId(User user, long applicationId) {
        Query q = em.createNamedQuery("getSchedulesByApplicationId");
        int dsDivisionId = user.getDsDivisions().iterator().next().getId();
        q.setParameter("dsDivisionId", dsDivisionId);
        q.setParameter("applicationId", applicationId);
        return q.getResultList();
    }

    @Transactional(propagation = Propagation.NEVER)
    public List<AppointmentSchedule> findSchedulesByApplicationId(User user, long applicationId) {
        Query q = em.createNamedQuery("getSchedulesListByApplicationId");
        q.setParameter("applicationId", applicationId);
        return q.getResultList();
    }

}
